package com.xhwl.data.config;

import com.xhwl.common.exception.DataException;
import com.xhwl.common.utils.DataVerifyUtil;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.regex.Pattern;

/**
 * @Author: luyi
 * @Description:
 * @Date: Create in 16:15 2023/2/21
 */
@Configuration
@Data
public class PwdConfig {

    /**
     * 值为 DataVerifyUtil 里面密码正则表达式的名称
     */
    @Value("${pwd.model:REGEX_PWD}")
    private String model;


    public void passwordCheck(String pwd){
        if(!match(pwd)){
            throw new DataException("密码格式不正确");
        }
    }

    private boolean match(String pwd){
        String pwdExpression = null;
        for (Field declaredField : DataVerifyUtil.class.getDeclaredFields()) {
            String currentFieldName = declaredField.getName();
            if(model.equals(currentFieldName)){
                declaredField.setAccessible(true);
                try {
                    pwdExpression = (String) declaredField.get(DataVerifyUtil.class);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
        return Pattern.matches(pwdExpression, pwd);
    }

}
